# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2022/7/10 21:24
# @Author : xyjiang1216
# @Email : jiangxuyan@nudt.edu.cn
# @File : inject_tbl_linker.py
# @Version: planner_builder 1.0
from lib.tsn_builder_lib import host_to_net
import xml.etree.ElementTree as EleTree

from tsn_builder_struct.inject_tbl_structure import InjectTbl, InjectTblEachNode, InjectEntry_union


def link_inject_tbl(node,
                    inject_tbl,
                    reg_addr):
    print('link_inject_tbl')
    node_id = node['src_node']

    #print(node_id)
    tbl_each_node = []
    for tbl in inject_tbl.tbl_set:
        if tbl.node_id == node_id:
            tbl_each_node = tbl.tbl_each_node
            break

    if not tbl_each_node:
        return []

    #print(len(tbl_each_node))

    addr = reg_addr.inject_tbl['addr']
    addr_str = host_to_net(addr)

    value_set = []

    for entry in tbl_each_node:
        value = entry.byte.entry1
        value_str = host_to_net(value)
        value_set.append(value_str)

    dic = [{'addr': addr_str,
            'value': value_set}]

    [print(entry) for entry in dic]
    return dic


def _get_inject_tbl(inject_tbl_xml):
    inform_set = []
    root = EleTree.parse(inject_tbl_xml)
    node_ele_set = root.findall('node')
    for node_ele in node_ele_set:
        node_dic = {}
        node_id = node_ele.findtext('node_id')
        node_dic.update({'node_id': int(node_id)})

        node_dic.update({'inject_set': []})

        entry_ele_set = node_ele.findall('entry')
        for entry_ele in entry_ele_set:
            entry_ele = list(entry_ele)
            entry_dic = {}
            for ele in entry_ele:
                entry_dic.update({ele.tag: int(ele.text)})
            node_dic['inject_set'].append(entry_dic)
        inform_set.append(node_dic)
    return inform_set


def _init_inject_tbl(inject_set):
    inject_tbl = InjectTbl()
    for node in inject_set:
        inject_tbl_each_node = InjectTblEachNode(node['node_id'])
        inject_set_each_node = node['inject_set']
        for entry in inject_set_each_node:
            inject_entry = InjectEntry_union()
            inject_entry.bit.valid = entry['valid']
            inject_entry.bit.reserved = entry['reserved']
            inject_entry.bit.dbuf_id = entry['dbuf_id']
            inject_entry.bit.time_slot = entry['time_slot']
            inject_tbl_each_node.append_entry(inject_entry)
        inject_tbl.append_tbl(inject_tbl_each_node)
    return inject_tbl


def read_inject_tbl(inject_tbl_xml):
    inject_set = _get_inject_tbl(inject_tbl_xml)
    # print('DEBUG')
    # [print(entry) for entry in inject_set]

    inject_tbl = _init_inject_tbl(inject_set)

    return inject_tbl


def main():
    inject_tbl_xml = '../output_xml/tbl_xml/inject_tbl.xml'
    read_inject_tbl(inject_tbl_xml)


if __name__ == '__main__':
    main()
